import 'dart:math';
import 'package:dio/dio.dart';
import 'car_model.dart';

class CarService {
  String getTitle() {
    final random = Random();
    const wordList = [
      '崔健',
      '唐朝',
      '黑豹',
      '鲍家街43号',
      '扭曲的机器',
      '超载',
      '面孔',
      '新裤子',
      '反光镜',
      '花儿',
      '黑撒',
      '痛仰',
      '刺猬',
      '回春丹',
      '重塑',
      '五条人',
      '盘尼西林',
      '二手玫瑰',
      '马赛克',
      'Joyside',
      '不速之客',
      'Beyond',
      '谢天笑',
      '野孩子',
      '许巍',
    ];
    return wordList[random.nextInt(wordList.length)];
  }

  Stream<CarModel?> getCarStream() async* {
    yield null; // 可选：立即发射一个空列表，表示加载开始（用于显示加载中状态）
    try {
      final response = await Dio().get(
        'https://api.chexun.com/searchV5',
        queryParameters: {"pn": 1, "ps": 20, "q": "车讯原创", "t": 0},
      );
      if (response.statusCode == 200) {
        final Map body = response.data;
        if (body.isEmpty) yield null;
        if (body.keys.contains('data')) {
          final Map data = body['data'];
          if (data.keys.contains('works')) {
            final List list = data['works'];
            if (list.isNotEmpty) {
              final CarModel car = CarModel.fromJson(body['data']['works'][0]);
              yield car;
            } else {
              yield null;
            }
          } else {
            yield null;
          }
        } else {
          yield null;
        }
      } else {
        throw Exception('Failed to load users: ${response.statusCode}');
      }
    } catch (e) {
      throw e;
    }
  }

  Future<CarModel?> fetchCar() async {
    final response = await Dio().get(
      'https://api.chexun.com/searchV5',
      queryParameters: {"pn": 1, "ps": 20, "q": "车讯原创", "t": 0},
    );
    if (response.statusCode == 200) {
      final Map body = response.data;
      if (body.isEmpty) return null;
      if (body.keys.contains('data')) {
        final Map data = body['data'];
        if (data.keys.contains('works')) {
          final List list = data['works'];
          if (list.isNotEmpty) {
            final CarModel car = CarModel.fromJson(body['data']['works'][0]);
            return car;
          } else {
            return null;
          }
        } else {
          return null;
        }
      } else {
        return null;
      }
    } else {
      throw Exception('加载用户失败: ${response.statusCode}');
    }
  }
}
